package com.program.houai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.program.houai.entity.*;
import com.program.houai.exception.BusinessException;
import com.program.houai.exception.ErrorType;
import com.program.houai.po.LoginUser;
import com.program.houai.redis.RedisService;
import com.program.houai.service.*;
import com.program.houai.util.DateFullUtils;
import com.program.houai.util.PageUtils;
import com.program.houai.util.PageVO;
import com.program.houai.util.R;
import com.program.houai.vo.*;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @version v1.0
 * @ProjectName: EOrder-master
 * @ClassName: UserController
 * @Description: TODO(一句话描述该类的功能)
 * @Author: Topcheer
 * @Date: 2024/8/29 8:56
 */
@Api(tags = "用户接口")
@RestController
@RequestMapping("/app/user")
@Slf4j
@Validated
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ICmallOrderGoodsService cmallOrderGoodsService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IUserRoyaltyService userRoyaltyService ;

    @Value("${system.order.royalty}")
    private int royalty;

    @Autowired
    private IUserVipCardService userVipCardService;

    @Autowired
    private IOrderRoyaltyService orderRoyaltyService;

    @Autowired
    private IChildUserVipCardService childUserVipCardService;

    @Value("${system.file.request-url}")
    private String requestUrl;

    @ApiOperation("注册微信用户")
    @PostMapping(value = "/registry", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Object> insertWxUser(@RequestBody UserEntity user) {
        boolean result =  userService.registryUserInfo(user);
        return R.ok(result);
    }

    @ApiOperation("订单列表")
    @PostMapping(value = "/orderList", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<PageUtils<UserOrderVO>> orderList(@RequestBody UserOrderListVO pageVO, @RequestHeader("token") String token) {

        LoginUser loginUser =  redisService.getLoginValueByToken(token);
        QueryWrapper<UserRoyaltyEntity> royaltyEntityWrap = new QueryWrapper<UserRoyaltyEntity>();
        royaltyEntityWrap.eq("user_id",loginUser.getId());
        UserRoyaltyEntity  userRoyaltyEntity =  userRoyaltyService.getOne(royaltyEntityWrap);
        int userRoyalty = royalty;
        if (userRoyaltyEntity != null){
            userRoyalty = userRoyaltyEntity.getRoyalty();
        }
        QueryWrapper<UserEntity> userWrap = new QueryWrapper<UserEntity>();
        userWrap.eq("pid",loginUser.getId());
        userWrap.eq("status",1);
        List<UserEntity>  userEntityList = userService.list(userWrap);
        List<Integer> idList = userEntityList.stream()
                .map(UserEntity::getAppUserId) // 将每个Person对象映射到它的name属性
                .collect(Collectors.toList()); // 收集结果到List<String>
        if (idList.isEmpty()){
            return R.ok();
        }
        IPage<UserOrderVO> page = new Page<>(pageVO.getPageNum(), pageVO.getPageSize());
        //已支付所有的订单，包含已结算何未结算
        String isRoyalty ="1";
        if (pageVO.getOrderStatus() == 2 || pageVO.getOrderStatus() == 99){
            page = userService.getAllOrderList(page,idList,pageVO.getOrderStatus(),null,null,null);
        //未结算
        }else if(pageVO.getOrderStatus() == 0){
            pageVO.setOrderStatus(2);
            isRoyalty ="0";
            page = userService.getAllOrderList(page,idList,pageVO.getOrderStatus(),isRoyalty,null,null);
        }else if (pageVO.getOrderStatus() == 1){
            pageVO.setOrderStatus(2);
            isRoyalty ="1";
            page = userService.getAllOrderList(page,idList,pageVO.getOrderStatus(),isRoyalty,null,null);
        }
        if (!page.getRecords().isEmpty()){
            List<Integer> orderIds = page.getRecords().stream()
                    .map(UserOrderVO::getOrderId)
                    .collect(Collectors.toList());
            QueryWrapper<CmallOrderGoodsEntity> wrap = new QueryWrapper<CmallOrderGoodsEntity>();
            wrap.eq("deleted",0);
            wrap.orderByDesc("add_time");
            wrap.in("order_id",orderIds);
            List<CmallOrderGoodsEntity>  orderDetail = cmallOrderGoodsService.list(wrap);
            Map<Integer, List<CmallOrderGoodsEntity>> map = orderDetail.stream()
                    .collect(Collectors.groupingBy(CmallOrderGoodsEntity::getOrderId));


            for (UserOrderVO userOrderVO : page.getRecords()){
                userOrderVO.setIsRoyalty(userOrderVO.getIsRoyalty());
                userOrderVO.setType(userOrderVO.getType());
                //已结算
                if (userOrderVO.getIsRoyalty() ==1){
                    userOrderVO.setCreateTime(userOrderVO.getRoyaltyTime());
                }else{
                    userOrderVO.setCreateTime(userOrderVO.getPaytime());
                }
                if (pageVO.getOrderStatus() == 99){
                    userOrderVO.setIsRoyalty(99);
                }
                List<MainUserOrderVO> detail = new ArrayList<>();
                if (userOrderVO.getType() == 1){
                    MainUserOrderVO mainUserOrderVO= new MainUserOrderVO();
                    mainUserOrderVO.setUrl(requestUrl+"static/moren.jpg");
                    mainUserOrderVO.setCount(1);
                    mainUserOrderVO.setGoodsName(userOrderVO.getTxndesc());
                    BigDecimal divisor = BigDecimal.valueOf(10000);
                    BigDecimal dividend = BigDecimal.valueOf( userOrderVO.getPrice()* userRoyalty);
                    BigDecimal yuan = dividend.divide(divisor, 2, RoundingMode.HALF_UP);
                    //佣金
                    mainUserOrderVO.setRoyalty(yuan.toString());
                    //订单总金额
                    BigDecimal divisor1 = BigDecimal.valueOf(100);
                    BigDecimal dividend1 = BigDecimal.valueOf( userOrderVO.getPrice());
                    BigDecimal price = dividend1.divide(divisor1, 2, RoundingMode.HALF_UP);
                    mainUserOrderVO.setOrderPrice(price.toString());
                    detail.add(mainUserOrderVO);
                }else{
                    // 商城订单
                    List<CmallOrderGoodsEntity>  orderList =   map.get(userOrderVO.getOrderId());
                    for (CmallOrderGoodsEntity cmallOrderGoodsEntity: orderList){
                        MainUserOrderVO mainUserOrderVO= new MainUserOrderVO();
                        BigDecimal divisor = BigDecimal.valueOf(100);
                        BigDecimal dividend = BigDecimal.valueOf( cmallOrderGoodsEntity.getPrice()* userRoyalty);
                        BigDecimal yuan = dividend.divide(divisor, 2, RoundingMode.HALF_UP);
                        mainUserOrderVO.setRoyalty(yuan.toString());

                        //double 金额
                        BigDecimal bigDecimal = new BigDecimal(String.valueOf(cmallOrderGoodsEntity.getPrice()));
                        BigDecimal yuan1 = bigDecimal.setScale(2, RoundingMode.HALF_UP);
                        mainUserOrderVO.setOrderPrice(yuan1.toString());
                        mainUserOrderVO.setGoodsName(cmallOrderGoodsEntity.getGoodsName());
                        mainUserOrderVO.setCount(cmallOrderGoodsEntity.getNumber());
                        mainUserOrderVO.setUrl(cmallOrderGoodsEntity.getPicUrl());
                        detail.add(mainUserOrderVO);
                    }
                }
                userOrderVO.setDetail(detail);
            }
        }

        return R.ok(new PageUtils(page));
    }

    @ApiOperation("首页中部统计数据")
    @PostMapping(value = "/statistics", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<StatisticsVO> statistics(@RequestHeader("token") String token) {
        LoginUser loginUser =  redisService.getLoginValueByToken(token);

        QueryWrapper<UserVipCardEntity> vipwrap = new QueryWrapper<UserVipCardEntity>();
        vipwrap.eq("user_id",loginUser.getId());
        //未激活
        vipwrap.eq("card_status",0);
        long count = userVipCardService.count(vipwrap);
        StatisticsVO statisticsVO = new StatisticsVO();
        statisticsVO.setCardCount(Long.toString(count));

        QueryWrapper<UserRoyaltyEntity> royaltyEntityWrap = new QueryWrapper<UserRoyaltyEntity>();
        royaltyEntityWrap.eq("user_id",loginUser.getId());
        UserRoyaltyEntity  userRoyaltyEntity =  userRoyaltyService.getOne(royaltyEntityWrap);
        int userRoyalty = royalty;
        if (userRoyaltyEntity != null){
            userRoyalty = userRoyaltyEntity.getRoyalty();
        }

        QueryWrapper<UserEntity> userWrap = new QueryWrapper<UserEntity>();
        userWrap.eq("pid",loginUser.getId());
        userWrap.eq("status",1);
        List<UserEntity>  userEntityList = userService.list(userWrap);
        statisticsVO.setUserCount(Long.toString(userEntityList.size()));
        List<Integer> idList = userEntityList.stream()
                .map(UserEntity::getAppUserId) // 将每个Person对象映射到它的name属性
                .collect(Collectors.toList()); // 收集结果到List<String>
        if (!idList.isEmpty()){
            //已支付的订单总数
            List<UserOrderVO> orderList =  userService.getAllOrderList(idList,2,null,null,null);
            statisticsVO.setOrderCount(Long.toString(orderList.size()));
            int totalMoney =
                    orderList.stream()
                            .mapToInt(UserOrderVO::getPrice)
                            .sum(); // 求和
            BigDecimal divisor = BigDecimal.valueOf(10000);
            BigDecimal dividend = BigDecimal.valueOf(totalMoney*userRoyalty);
            // 除法运算，并设置保留两位小数，以及四舍五入的模式
            BigDecimal money = dividend.divide(divisor, 2, RoundingMode.HALF_UP);
            statisticsVO.setRoyalty(money.toString());
        }else{
            statisticsVO.setRoyalty("0");
            statisticsVO.setOrderCount("0");
        }
        return R.ok(statisticsVO);
    }

    @ApiOperation("主页轮播图")
    @PostMapping(value = "/lunboList", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<List<String>> lunboList() {
        List<String>  picList = new ArrayList<>();
        picList.add(requestUrl+"static/lunbo1.png");
        picList.add(requestUrl+"static/lunbo2.png");
        picList.add(requestUrl+"static/lunbo3.png");
        return R.ok(picList);
    }

    @ApiOperation("获取个人信息")
    @PostMapping(value = "/getPersonalInformation", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<UserEntity> getPersonalInformation( @RequestHeader("token") String token) {
        LoginUser loginUser =  redisService.getLoginValueByToken(token);
        UserEntity userEntity=  userService.getById(loginUser.getId());
        if (StringUtils.isBlank(userEntity.getAvatarUrl())){
            userEntity.setAvatarUrl(requestUrl+"static/user/avatar.png");
        }else {
            userEntity.setAvatarUrl(userEntity.getAvatarUrl());
        }
        QueryWrapper<UserEntity> userWrap = new QueryWrapper<UserEntity>();
        userWrap.eq("pid",loginUser.getId());
        userWrap.eq("status",1);
        List<UserEntity>  userEntityList = userService.list(userWrap);
        List<Integer> idList = userEntityList.stream()
                .map(UserEntity::getAppUserId) // 将每个Person对象映射到它的name属性
                .collect(Collectors.toList()); // 收集结果到List<String>
        QueryWrapper<UserRoyaltyEntity> royaltyEntityWrap = new QueryWrapper<UserRoyaltyEntity>();
        royaltyEntityWrap.eq("user_id",loginUser.getId());
        UserRoyaltyEntity  userRoyaltyEntity =  userRoyaltyService.getOne(royaltyEntityWrap);
        int userRoyalty = royalty;
        if (userRoyaltyEntity != null){
            userRoyalty = userRoyaltyEntity.getRoyalty();
        }
        //今日数据
        String toDay= DateFullUtils.getDateStr(new Date());
        String startTime= toDay+" 00:00:00";
        String endTime =toDay+" 23:59:59";
        List<UserOrderVO>  todayList = userService.getAllOrderList(idList,2,null,startTime,endTime);
        int todayMoney =
                todayList.stream()
                .mapToInt(UserOrderVO::getPrice)
                .sum(); // 求和
        BigDecimal divisor = BigDecimal.valueOf(10000);
        BigDecimal dividend = BigDecimal.valueOf(todayMoney*userRoyalty);
        // 除法运算，并设置保留两位小数，以及四舍五入的模式
        BigDecimal money = dividend.divide(divisor, 2, RoundingMode.HALF_UP);
        userEntity.setTodayMoney(money.toString());
        //昨日数据
        String yesDay= DateFullUtils.getDateStr(DateFullUtils.diffDate(new Date(),1));
        String ysStartTime= yesDay+" 00:00:00";
        String ysEndTime =yesDay+" 23:59:59";

        List<UserOrderVO> yesVOList = userService.getAllOrderList(idList,2,null,ysStartTime,ysEndTime);
        int yestMoney =
                yesVOList.stream()
                        .mapToInt(UserOrderVO::getPrice)
                        .sum(); // 求和
        BigDecimal dividend1 = BigDecimal.valueOf(yestMoney*userRoyalty);
        BigDecimal money1 = dividend1.divide(divisor, 2, RoundingMode.HALF_UP);
        userEntity.setYestMoney(money1.toString());

        BigDecimal divisor2 = BigDecimal.valueOf(100);
        BigDecimal dividend2= BigDecimal.valueOf(userEntity.getMoney());
        // 除法运算，并设置保留两位小数，以及四舍五入的模式
        BigDecimal mountMoney = dividend2.divide(divisor2, 2, RoundingMode.HALF_UP);
        userEntity.setMountMoney(mountMoney.toString());

        return R.ok(userEntity);
    }


    @ApiOperation("修改个人信息")
    @PostMapping(value = "/updateUserInformation", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<UserEntity> updateUserInformation(@RequestBody UserEntity user , @RequestHeader("token") String token) {
        LoginUser loginUser =  redisService.getLoginValueByToken(token);
        user.setId(loginUser.getId());
        userService.updateById(user);
        return R.ok();
    }


    @ApiOperation("我的会员")
    @PostMapping(value = "/getChildUser", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<PageUtils<ChildUserVipCardVO>> getChildUser(@RequestBody ChildUserCardVO childUserCardVO ,@RequestHeader("token") String token) {
        IPage<ChildUserVipCardVO> page = new Page<>(childUserCardVO.getPageNum(), childUserCardVO.getPageSize());
        LoginUser loginUser =  redisService.getLoginValueByToken(token);
        String endTime = "";
        if (!StringUtils.isBlank(childUserCardVO.getEndTime())){
            endTime = childUserCardVO.getEndTime()+" 23:59:59";
        }else{
            endTime = null;
        }
        page = childUserVipCardService.getChildUserList(page,loginUser.getId(),
                StringUtils.isBlank(childUserCardVO.getLevel())? null:childUserCardVO.getLevel(),endTime);
        for (ChildUserVipCardVO childUserVipCardVO : page.getRecords()){
            childUserVipCardVO.setUrl(requestUrl+"static/myVip/"+childUserVipCardVO.getLevel()+".png");
        }
         return R.ok(new PageUtils(page));
    }

    @ApiOperation("H5注册用户")
    @PostMapping(value = "/h5Registry", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Object> h5registry(@RequestBody H5UserVO h5UserVO) {
        boolean result =  userService.h5Registry(h5UserVO);
        return R.ok(result,"操作成功！");
    }

}
